<?php

namespace app\api\model;

use Alipay\EasySDK\Kernel\Factory as alipayFactory;
use app\admin\model\Coupon;
use app\admin\model\UserCash;
use app\admin\model\UserCoupon;
use app\admin\model\UserMoneyLog;
use app\common\library\IdentityCard;
use app\common\library\Token;
use app\common\model\BaseModel;
use app\common\model\Config;
use app\common\model\Sms;
use EasyWeChat\Factory;
use fast\Random;
use think\db\Query;
use think\facade\Db;
use think\facade\Validate;
use app\api\validate\Driver;

class User extends BaseModel
{
    // 表名
    protected $name = 'user';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
    ];

    /**
     * 微信或支付宝小程序登录
     * @param $requestData
     * @return array|string[]
     */
    public function wechatLogin($requestData){
        $type = $requestData['type']??1;
        // 配置
        $config    =  Config::where('group', 'basic')->column('value', 'name');
        if($type == 1){
            $code = $requestData['code']??'';
            $encryptedData = $requestData['encryptedData']??'';
            $iv = $requestData['iv']??'';
            $agreement = $requestData['agreement']??0;
            if(empty($code)  || empty($encryptedData)|| empty($iv) || !$agreement){
                return ['status'=>'0','message'=>'参数错误','result'=>''];
            }
            $wechat_config = config("config_wechat.mini_program");
            if(!$wechat_config){
                return ['status'=>'0','message'=>'请求错误','result'=>''];
            }
            $app = Factory::miniProgram($wechat_config);
            //根据code获取用户 session信息
            $user_data = $app->auth->session($code);
            //解密信息
            $decryptedData = $app->encryptor->decryptData($user_data['session_key'], $iv, $encryptedData);
            $wx_openid =  $user_data['openid'];   //微信openid
//        $nickname  =  $decryptedData['nickName'];  //微信昵称
//        $head_img  =  $decryptedData['avatarUrl']; //微信头像
            $user_mes = $this->userFind(['openid'=>trim($wx_openid)]);
            $nickname  =  $config['nickname'];  //微信昵称
            $head_img  =  $config['avatar']; //微信头像
        }else{
            $code = $requestData['code']??'';
            if(!$code){
                return ['status'=>'0','message'=>'参数错误','result'=>''];
            }
            alipayFactory::setOptions(getOption());
            //code换取auth_token
            $textParams = array(
                "grant_type" => "authorization_code",
                "code" => $code,
            );
            //设置业务参数（OpenAPI中biz_content里的参数）
            $bizParams = array();
            $resJson = alipayFactory::util()->generic()->execute("alipay.system.oauth.token", $textParams, $bizParams)->httpBody;
            $resJsonToArray = json_decode($resJson, true);
            if(!$resJsonToArray){
                return ['status'=>'0','message'=>'请求失败','result'=>''];
            }
            if (!isset($resJsonToArray['alipay_system_oauth_token_response'])) {
                return ['status'=>'0','message'=>'请求失败','result'=>$resJsonToArray['error_response']['sub_msg']];
            }
            $auth_token = $resJsonToArray['alipay_system_oauth_token_response'];
            //设置系统参数（OpenAPI中非biz_content里的参数）
            $textParams = array(
                "auth_token" => $auth_token['access_token']
            );
            //设置业务参数（OpenAPI中biz_content里的参数）
            $bizParams = array();
            $resJson = alipayFactory::util()->generic()->execute("alipay.user.info.share", $textParams, $bizParams)->httpBody;
            $resJsonToArray = json_decode($resJson, true);
            if (!isset($resJsonToArray['alipay_user_info_share_response'])) {
                return ['status'=>'0','message'=>'请求失败','result'=>'获取失败'];
            }
            if ($resJsonToArray['alipay_user_info_share_response']['code'] != "10000") {
                return ['status'=>'0','message'=>'请求失败','result'=>$resJsonToArray['alipay_user_info_share_response']['sub_msg']];
            }
            $data = [
                "avatar" => $resJsonToArray['alipay_user_info_share_response']['avatar'],
                "nick_name" => $resJsonToArray['alipay_user_info_share_response']['nick_name'],
                "user_id" => $resJsonToArray['alipay_user_info_share_response']['user_id'],
            ];
            $nickname  =  $data['nick_name'];  //默认昵称
            $head_img  =  $data['avatar']; //默认头像
            $user_mes = $this->userFind(['alipayid'=>trim($data['user_id'])]);
        }
        //上级uid
        $pid = $requestData['pid']??0;
        //记录本次登录的IP和时间
        $ip = request()->ip();
        $logintime = time();
        if(!empty($user_mes)){
            //登录
            $login_type = 2; //操作类型： 1 注册  2 登录
            $user_id = $user_mes['id'];
            User::update(['updatetime' => time(), 'loginip' => $ip, 'logintime' => $logintime], ['id'=>$user_id]);
        }else{
            //注册
            $login_type = 1; //操作类型： 1 注册  2 登录
            //组装数据
            $insertData = [
                "username"=>$nickname,
                "avatar"=>$head_img,
                "createtime"=>time(),
                'loginip' => $ip,
                'logintime' => $logintime,
                'status' => 'normal',
                'jointime' => time(),
                'joinip' => $ip,
                'user_type' => $type
            ];
            if($type == 1){
                $insertData['openid'] = $wx_openid;
            }else{
                $insertData['alipayid'] = $data['user_id'];
            }
            $user_id = User::insertGetId($insertData);
            if($type == 1){
                $new_nickname = str_pad($nickname.$user_id, 13, Random::numeric(7));
                User::where('id', $user_id)->update(['username' => $new_nickname]);
            }
            //有上级uid  上级获得红包
            $register_money = \app\api\model\Config::where('name', 'register_money')->value('value');
            if($pid && $register_money && $register_money > 0){
                $parent = User::where('id', $pid)->find();
                if($parent){
                    User::where('id', $pid)->inc('money', $register_money)->update();
                    $new_money = bcadd($register_money, $parent['money'], 2);
                    $user_money_log = [
                        'user_id' => $pid,
                        'money' => $register_money,
                        'before' => $parent['money'],
                        'after' => $new_money,
                        'memo' => '注册分销收入',
                        'createtime' => time(),
                        'type' => 2,
                        'source_uid' => $user_id,
                    ];
                    UserMoneyLog::insert($user_money_log);
                    //写入用户分销收入表
                    $user_income = [
                        'user_id' => $pid,
                        'source_uid' => $user_id,
                        'amount' => $register_money,
                        'type' => 1,
                        'createtime' => time()
                    ];
                    UserIncome::insert($user_income);
                }
            }
        }

        //查询用户信息
        $wx_user_mes = $this->userFind(['id' => $user_id], 'id,username,avatar');
        //不存在生成邀请码
        if(!$wx_user_mes['invitation_code']){
            if($type == 1){//微信
                $app = Factory::miniProgram($wechat_config);
                $path = 'pages/index/index';
                $param = $user_id;
                $response = $app->app_code->getUnlimit($param,['page'=>$path,'env_version'=>'release','check_path'=>false]);
                if($response instanceof \EasyWeChat\Kernel\Http\StreamResponse){
                    $img_name = 'appcode'.$user_id.'.png';
                    $filename = $response->saveAs($_SERVER['DOCUMENT_ROOT'].'/uploads/user/',$img_name);
                }
                User::where(['id'=>$user_id])->update(['invitation_code'=>'/uploads/user/'.$img_name]);
            }else{//支付宝
                alipayFactory::setOptions(getOption());
                $resJson = alipayFactory::base()->qrcode()->create('page/index/index', $user_id, '用户分销码')->httpBody;
                $resJsonToArray = json_decode($resJson, true);
                if(!$resJsonToArray){
                    return ['status'=>'0','message'=>'请求失败','result'=>''];
                }
                if (!isset($resJsonToArray['alipay_open_app_qrcode_response'])) {
                    return ['status'=>'0','message'=>'请求失败','result'=>$resJsonToArray['error_response']['sub_msg']];
                }
                $qr_code_url = $resJsonToArray['qr_code_url'];
                User::where(['id'=>$user_id])->update(['invitation_code'=>$qr_code_url]);
            }

        }

        $token = Random::uuid();
        Token::set($token, $wx_user_mes['id'], 2592000);

        //登录成功的事件
//        event("user_login", $wx_user_mes);
        $result_data = array(
            'login_type'=>$login_type,
            'user_mes'=>$wx_user_mes,
            'token' => $token,
            'role_type' => $type
        );
        return ['status' => 1, 'message' => '登录成功', 'result' => $result_data];
    }

    /**
     * 优惠券弹窗
     */
    public function couponCheck($requestData, $user){
        if(!$user){
            return ['status' => 0, 'message' => '用户不存在', 'result' => ''];
        }
        //其他优惠券
        $other_coupon = Coupon::field('id,coupon_name,coupon_amount,coupon_limit,limit_type,days,type')->where(['is_delete' => 1, 'status' => 1, 'is_eject' => 2, 'type' => [1,2]])->where('coupon_time', '>', time())->find();
        $data = [];
        if($other_coupon){
            $other_coupon['coupon_amount'] = floatval($other_coupon['coupon_amount']);
            $user_coupon = UserCoupon::where(['is_delete' => 1, 'user_id' => $user['id'], 'coupon_id' => $other_coupon['id']])->count();
            if($user_coupon == 0){
                $data = $other_coupon;
            }
        }
        //新人优惠券
        $new_coupon = Coupon::field('id,coupon_name,coupon_amount,coupon_limit,limit_type,days,type')->where(['is_delete' => 1, 'status' => 1, 'is_eject' => 2, 'type' => 3])->where('coupon_time', '>', time())->find();
        if($new_coupon){
            $new_coupon['coupon_amount'] = floatval($new_coupon['coupon_amount']);
            $user_coupon = UserCoupon::where(['is_delete' => 1, 'user_id' => $user['id'], 'coupon_id' => $new_coupon['id']])->count();
            if($user_coupon == 0){
                $data = $new_coupon;
            }
        }
        return ['status' => 1, 'message' => '操作成功', 'result' => $data];
    }

    /**
     * 优惠券领取
     */
    public function couponReceive($requestData, $user){
        if(!$user){
           return ['status' => 0, 'message' => '用户不存在', 'result' => ''];
        }
        $coupon_id = $requestData['coupon_id']??0;
        if(!$coupon_id){
            return ['status' => 0, 'message' => '参数错误', 'result' => ''];
        }
        $coupon = Coupon::field('id,start_time,coupon_name,coupon_amount,coupon_limit,limit_type,days,type,coupon_time')->where(['is_delete' => 1, 'status' => 1, 'is_eject' => 2, 'type' => 3])->find()->toArray();
        if(!$coupon){
            return ['status' => 0, 'message' => '优惠券不存在', 'result' => ''];
        }
        if($coupon['coupon_time'] < time()){
            return ['status' => 0, 'message' => '优惠活动已截止', 'result' => ''];
        }
        $user_coupon = UserCoupon::where(['is_delete' => 1, 'user_id' => $user['id'], 'coupon_id' => $coupon_id])->count();
        if($user_coupon){
            return ['status' => 0, 'message' => '此优惠券您已领取过', 'result' => ''];
        }
        $insert_data = [
            'user_id' => $user['id'],
            'coupon_id' => $coupon_id,
            'coupon_name' => $coupon['coupon_name'],
            'coupon_amount' => $coupon['coupon_amount'],
            'coupon_limit' => $coupon['coupon_limit'],
            'coupon_type' => $coupon['limit_type'],
            'type' => $coupon['type'],
            'createtime' => time(),
            'expiration_time' => $coupon['coupon_time'],
            'start_time' => $coupon['start_time']
        ];
        $res = UserCoupon::insert($insert_data);
        if($res){
            return ['status' => 1, 'message' => '操作成功', 'result' => ''];
        }else{
            return ['status' => 0, 'message' => '操作失败', 'result' => ''];
        }
    }

    /**
     * 我的首页
     */
    public function mine($requestData, $user){
        if(!$user){
            return ['status' => 0, 'message' => '用户不存在', 'result' => ''];
        }
        $certified_list = [1 => '未认证', 2 => '待审核', 3 => '已通过', 4 => '已驳回'];
        $service_phone = Config::where('name', 'service_phone')->value('value');
        $data = [
            'username' => $user['username']??'',
            'avatar' => $user['avatar']??'',
            'truename' => $user['truename']??'',
            'id_card' => $user['id_card']??'',
            'is_certified' => $user['is_certified'],
            'certified_text' => $certified_list[$user['is_certified']],
            'service_phone' => $service_phone,
            'back_image' => Config::where('name', 'back_image')->value('value')
        ];
        return ['status' => 1, 'message' => '操作成功', 'result' => $data];
    }

//    /**
//    *  原实名认证
//    */
//    public function certified($requestData, $user){
//        $type = $requestData['type']??0;
//        if(!$type){
//            return ['status'=>'0','message'=>'请求类型错误','result'=>''];
//        }
//        if($type == 2){
//            $id_card = $requestData['id_card']??'';
//            $true_name = $requestData['truename']??'';
//            if(!$id_card || !$true_name){
//                return ['status'=>'0','message'=>'参数错误','result'=>''];
//            }
//            //验证身份证
//            $IdentityCard = new IdentityCard();
//            if(!$IdentityCard->checkIdentity($id_card)){
//                return ['status'=>'0','message'=>'身份证号错误','result'=>''];
//            }
//            //判断身份证年龄
//            $age = $IdentityCard->getAgeFromIdNo($id_card);
//            if($age < 18){
//                return ['status'=>'0','message'=>'未满18周岁，无法认证','result'=>''];
//            }
//            if(isset($user['is_certified']) && in_array($user['is_certified'], [2,3])){
//                return ['status'=>'0','message'=>'认证已提交或已通过','result'=>''];
//            }
//            $update_user = ['id_card' => $id_card, 'truename' => $true_name, 'is_certified' => 2, 'updatetime' => time()];
//            $result = self::where('id', $user['id'])->update($update_user);
//            if ($result) {
//                $update_user['id'] = $user['id'];
//                return ['status'=>'1','message'=>'提交成功','result'=>$update_user];
//            }else{
//                return ['status'=>'0','message'=>'提交失败','result'=>''];
//            }
//        }else{
//            return ['status'=>'1','message'=>'提交成功','result'=>['id' => $user['id'], 'username' => $user]];
//        }
//    }

    /**
     *  实名认证
     */
    public function certified($requestData, $user){
        $type = $requestData['type']??0;
        if(!$type){
            return ['status'=>'0','message'=>'请求类型错误','result'=>''];
        }
        if($type == 2){
            $idcard_front = $requestData['idcard_front']??'';
            $idcard_back = $requestData['idcard_back']??'';
            $mobile = $requestData['mobile']??'';
            if(!$idcard_front || !$idcard_front || !$mobile){
                return ['status'=>'0','message'=>'参数错误','result'=>''];
            }
            if(!preg_match('/^1[3456789]\d{9}$/ims',$mobile)){
                return ['status' => 0, 'message' => '手机号格式错误', 'result' => ''];
            }
            $update_user = ['idcard_front' => $idcard_front, 'idcard_back' => $idcard_back, 'mobile' => $mobile, 'is_certified' => 3, 'updatetime' => time()];
            $domain_url = request()->domain();
            //OCR识别接口
            $res = ocr_certified($domain_url . $idcard_front);
            if(!isset($res['status']) || $res['status'] != 'OK'){
                return ['status' => 0, 'message' => '认证失败', 'result' => ''];
            }
            $update_user['id_card'] = $res['result']['number'];
            $update_user['truename'] = $res['result']['name'];
            //三要素接口
            $res = three_certified($update_user['truename'], $update_user['id_card'], $mobile);
            if(!isset($res['status']) || !isset($res['state']) || $res['status'] != 'OK' || $res['state'] != 1){
                return ['status' => 0, 'message' => '认证失败', 'result' => ''];
            }
            $result = self::where('id', $user['id'])->update($update_user);
            if ($result) {
                $update_user['id'] = $user['id'];
                return ['status'=>'1','message'=>'提交成功','result'=>$update_user];
            }else{
                return ['status'=>'0','message'=>'提交失败','result'=>''];
            }
        }else{
            return ['status'=>'1','message'=>'提交成功','result'=>['id' => $user['id'], 'username' => $user]];
        }
    }

    /**
     *  修改用户资料
     */
    public function information($requestData, $user){
        $username = $requestData['username']??'';
        $type = $requestData['type']??0;
        if(!$type){
            return ['status'=>'0','message'=>'请求类型错误','result'=>''];
        }
        if($type == 2){
            if(!$username){
                return ['status'=>'0','message'=>'参数错误','result'=>''];
            }
            $update_user = ['username' => $username, 'updatetime' => time()];
            $result = self::where('id', $user['id'])->update($update_user);
            if ($result) {
                $update_user['id'] = $user['id'];
                return ['status'=>'1','message'=>'提交成功','result'=>$update_user];
            }else{
                return ['status'=>'0','message'=>'提交失败','result'=>''];
            }
        }else{
            return ['status'=>'1','message'=>'提交成功','result'=>['id' => $user['id'], 'username' => $user]];
        }
    }

    /**
     * 驾驶人列表
     */
    public function driverList($requestData, $user){
        $page = $requestData['page']??1;
        $limit = $requestData['limit']??10;
        $list = \app\api\model\Driver::getList(['user_id' => $user['id']], 'id,driver_name,driver_number', $page, $limit);
        return ['status' => 1, 'message' => '操作成功', 'result' => $list];
    }

    /**
     *  驾驶人新增或编辑
     */
    public function driverEdit($requestData, $user){
        $type = $requestData['type']??0;
        if(!$type || !in_array($type, [1,2])){
            return ['status' => 0, 'message'=>'请求类型错误', 'result' => ''];
        }
        $validate = new Driver();
        $scene = $type == 1 ? 'add' : 'edit';
        if (!$validate->scene($scene)->check($requestData)) {
            return ['status' => 0, 'message'=>$validate->getError(), 'result' => ''];
        }
        $update = ['user_id' => $user['id'], 'driver_name' => $requestData['driver_name'], 'driver_number' => $requestData['driver_number']];
        if($type == 1){
            $update['createtime'] = time();
        }else{
            $update['updatetime'] = time();
        }
        $driver_model = new \app\api\model\Driver();
        if($type == 1){
            $result = $driver_model->insert($update);
        }else{
            $result = $driver_model->where('id', $requestData['id'])->update($update);
        }
        if ($result) {
            return ['status'=>'1','message'=>'提交成功','result'=>''];
        }else{
            return ['status'=>'0','message'=>'提交失败','result'=>''];
        }
    }

    /**
     *  驾驶人删除
     */
    public function driverDelete($requestData, $user){
        $id = $requestData['id']??0;
        $driver = \app\api\model\Driver::getFind(['id' => $id, 'user_id' => $user['id']]);
        if(!$id || !$driver){
            return ['status' => 0, 'message'=>'驾驶人不存在', 'result' => ''];
        }
        $result = \app\api\model\Driver::where('id', $id)->delete();
        if ($result) {
            return ['status'=>'1','message'=>'删除成功','result'=>''];
        }else{
            return ['status'=>'0','message'=>'删除失败','result'=>''];
        }
    }

    /**
     * 地址列表
     */
    public function addressList($requestData, $user){
        $page = $requestData['page']??1;
        $limit = $requestData['limit']??10;
        $list = Address::getList(['user_id' => $user['id']], 'id,address_name,address_phone,concat(province, city, area, street) as address_data', 'createtime desc', $page, $limit);
        return ['status' => 1, 'message' => '操作成功', 'result' => $list];
    }

    /**
     *  地址新增
     */
    public function addressAdd($requestData, $user){
        $validate = new \app\api\validate\Address();
        if (!$validate->scene('add')->check($requestData)) {
            return ['status' => 0, 'message'=>$validate->getError(), 'result' => ''];
        }
        $address_data = explode(' ', $requestData['address_data']);
        $update = [
            'user_id' => $user['id'],
            'address_name' => $requestData['address_name'],
            'address_phone' => $requestData['address_phone'],
            'street' => $requestData['address_street'],
            'province' => $address_data[0]??'',
            'city' => $address_data[1]??'',
            'area' => $address_data[2]??'',
            'createtime' => time()
        ];
        $result = Address::insert($update);
        if ($result) {
            return ['status'=>'1','message'=>'新增成功','result'=>''];
        }else{
            return ['status'=>'0','message'=>'新增失败','result'=>''];
        }
    }

    /**
     *  地址编辑
     */
    public function addressEdit($requestData, $user){
        $type = $requestData['type']??0;
        if(!$type){
            return ['status'=>'0','message'=>'请求类型错误','result'=>''];
        }
        $id = $requestData['id']??0;
        $data = Address::getFind(['id' => $id, 'user_id' => $user['id']]);
        if(!$data){
            return ['status'=>'0','message'=>'地址不存在','result'=>''];
        }
        if($type == 2){
            $validate = new \app\api\validate\Address();
            if (!$validate->scene('edit')->check($requestData)) {
                return ['status' => 0, 'message'=>$validate->getError(), 'result' => ''];
            }
            $address_data = explode(' ', $requestData['address_data']);
            $update = [
                'user_id' => $user['id'],
                'address_name' => $requestData['address_name'],
                'address_phone' => $requestData['address_phone'],
                'street' => $requestData['address_street'],
                'province' => $address_data[0]??'',
                'city' => $address_data[1]??'',
                'area' => $address_data[2]??'',
                'updatetime' => time()
            ];
            $result = Address::where('id', $requestData['id'])->update($update);
            if ($result) {
                $update['id'] = $id;
                return ['status'=>'1','message'=>'编辑成功','result'=>$update];
            }else{
                return ['status'=>'0','message'=>'编辑失败','result'=>''];
            }
        }else{
            return ['status'=>'1','message'=>'请求成功','result'=>$data];
        }
    }

    /**
     *  地址删除
     */
    public function addressDelete($requestData, $user){
        $id = $requestData['id']??0;
        $address = Address::getFind(['id' => $id, 'user_id' => $user['id']]);
        if(!$id || !$address){
            return ['status' => 0, 'message'=>'地址不存在', 'result' => ''];
        }
        $result = Address::where('id', $id)->delete();
        if ($result) {
            return ['status'=>'1','message'=>'删除成功','result'=>''];
        }else{
            return ['status'=>'0','message'=>'删除失败','result'=>''];
        }
    }

    /**
     *  申请加盟
     */
    public function apply($requestData, $user){
        $validate = new \app\api\validate\Merchant();
        if (!$validate->scene('apply')->check($requestData)) {
            return ['status' => 0, 'message'=>$validate->getError(), 'result' => ''];
        }
        $merchant = Merchant::where(['merchant_phone' => $requestData['merchant_phone'], 'is_delete' => 1])->whereIn('examine_status', '1,2')->count();
        if($merchant){
            return ['status' => 0, 'message'=>'该商家手机号已存在', 'result' => ''];
        }
        $coordinate = explode(',', $requestData['coordinate']);
        //地址解析
        $address_data = getAddress($requestData['shop_address']);
        $logo = Config::where('name', 'logo')->value('value');
        $update = [
            'shop_name' => $requestData['shop_name'],
            'merchant_name' => $requestData['merchant_name'],
            'merchant_phone' => $requestData['merchant_phone'],
            'street' => $address_data['street']??'',
            'province' => $address_data['province']??'',
            'city' => $address_data['city']??'',
            'area' => $address_data['area']??'',
            'createtime' => time(),
            'longitude' => $coordinate[0],
            'latitude' => $coordinate[1],
            'shop_logo' => $logo
        ];
        $result = Merchant::insert($update);
        if ($result) {
            return ['status'=>'1','message'=>'申请成功','result'=>$update];
        }else{
            return ['status'=>'0','message'=>'申请失败','result'=>''];
        }
    }

    /**
     * 邀请有礼
     */
    public function invitation($requestData, $user){
        $page = $requestData['page']??1;
        $limit = $requestData['limit']??10;
        $list = User::field('id,avatar,username,createtime')->where('parent_id', $user['id'])->order('createtime', 'desc')->page($page, $limit)->select()->toArray();
        if($list){
            foreach ($list as $key=>$value){
                $income = UserIncome::where(['user_id' => $user['id'], 'source_uid' => $value['id']])->sum('amount');
                $list[$key]['createtime'] = date('Y-m-d H:i:s', $value['createtime']);
                $list[$key]['income'] = $income;
            }
        }
        $data = [
            'user_money' =>$user['money'],
            'invitation_code' =>$user['invitation_code'],
            'list' => $list,
            'money' => $user['money']
        ];
        return ['status' => 1, 'message' => '操作成功', 'result' => $data];
    }

    /**
     * 提现明细
     */
    public function cashList($requestData, $user){
        $page = $requestData['page']??1;
        $limit = $requestData['limit']??10;
        $list = UserCash::field('id,amount,fee,cash_amount,status,createtime,reason')->where(['is_delete' => 1, 'user_id' => $user['id']])->page($page,$limit)->select()->toArray();
        if($list){
            foreach ($list as &$value){
                $value['createtime'] = date('Y-m-d H:i:s', $value['createtime']);
                $value['amount'] = floatval($value['amount']);
                $value['fee'] = floatval($value['fee']);
                $value['cash_amount'] = floatval($value['cash_amount']);
            }
            unset($value);
        }
        return ['status' => 1, 'message' => '操作成功', 'result' => $list];
    }

    /**
     * 提现
     */
    public function cash($requestData, $user){
        $amount = $requestData['amount']??0;
        if(!$amount || $amount <= 0){
            return ['status' => 0, 'message' => '提现金额错误', 'result' => ''];
        }
        if($amount > $user['money']){
            return ['status' => 0, 'message' => '余额不足', 'result' => ''];
        }
        $last_cash_time = UserCash::where(['user_id' => $user['id']])->order('createtime', 'desc')->value('createtime');
        if($last_cash_time && $last_cash_time + 10 > time()){
            return ['status' => 0, 'message' => '请求频繁', 'result' => ''];
        }
        Db::startTrans();
        try {
            $user_cash_rate = \app\api\model\Config::where('name', 'user_cash_rate')->value();
            $fee = 0;
            if($user_cash_rate){
                $fee = bcmul($amount, $user_cash_rate/100, 2);
            }
            $cash = [
                'user_id' => $user['id'],
                'out_trade_no' => self::getCashOutTradeNo(),
                'amount' => $amount,
                'fee' => $fee,
                'cash_amount' => bcsub($amount, $fee, 2),
                'createtime' => time(),
            ];
            $result = UserCash::insert($cash);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return ['status' => 0, 'message' => $e->getMessage(), 'result' => ''];
        }
        if($result){
            return ['status' => 1, 'message' => '提现成功', 'result' => $result];
        }else{
            return ['status' => 0, 'message' => '提现失败', 'result' => ''];
        }
    }

    /**
     * 用户优惠券
     */
    public function couponList($requestData, $user){
        $page = $requestData['page']??1;
        $limit = $requestData['limit']??10;
        $merchant_id = $requestData['merchant_id']??0;
        if(!$merchant_id){//我的-优惠券列表
            $list = \app\api\model\UserCoupon::field('id,coupon_id,coupon_name,coupon_amount,coupon_limit,coupon_type,type,createtime,expiration_time,status,start_time,expiration_time')->where(['is_delete' => 1, 'user_id' => $user['id']])->page($page, $limit)->select()->toArray();
        }else{//提交订单页-优惠券列表
            $merchant = Merchant::where(['is_delete' => 1, 'id' => $merchant_id])->find();
            if(!$merchant){
                return ['status' => 0, 'message' => '商家不存在', 'result' => ''];
            }
            $coupon_ids = $merchant['coupon_ids'];
            if($coupon_ids){
                $list = \app\api\model\UserCoupon::field('id,coupon_id,coupon_name,coupon_amount,coupon_limit,coupon_type,type,createtime,expiration_time,status,start_time,expiration_time')->where(['is_delete' => 1, 'user_id' => $user['id'], 'status' => 1])->where("`type`=3 or (`type`<3 and `coupon_id` in ($coupon_ids))")->where('start_time', '<', time())->where('expiration_time', '>', time())->page($page, $limit)->select()->toArray();
            }else{
                $list = [];
            }

        }
        foreach ($list as $key=>$value){
            $value['coupon_amount'] = floatval($value['coupon_amount']);
            $value['createtime'] = date('Y-m-d H:i:s', $value['createtime']);
            $value['expiration_time'] = date('Y-m-d H:i:s', $value['expiration_time']);
            $list[$key] = $value;
        }
        return ['status' => 1, 'message' => '操作成功', 'result' => $list];
    }

    /**
     * @param array $where
     * @param string $field
     * @return array|mixed|\think\Model|null
     */
    public function userFind($where = [], $field = '*'){
        return $this->where($where)->field($field)->find();
    }

    //生成唯一提现订单号
    public static function getCashOutTradeNo(){
        $out_trade_no = sys_create_orderno(9);
        $order = UserCash::where('out_trade_no', $out_trade_no)->count();
        if($order){
            return self::getCashOutTradeNo();
        }
        return $out_trade_no;
    }

}
